//
//  MessageViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/26.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class MessageViewController: UIViewController {

    let disposeBag = DisposeBag()
    
    let db = SystemMessageDB.getShareInstance()
    
    var messages: [SystemMessage] = []
    
    var orderVM: OrderViewModel?
    
    fileprivate lazy var tableview: UITableView = {
        var tableview = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height - 64))
        tableview.delegate = self
        tableview.dataSource = self
        tableview.backgroundColor = lightSaperatorColor
        tableview.register(MessageTableViewCell.self, forCellReuseIdentifier: "MessageTableViewCell")
        tableview.separatorStyle = .none
        return tableview
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        self.navigationItem.title = LanguageHelper.getString(key: "MSG_LIST")
        
        setBackBarItem()
        
        view.addSubview(tableview)
        
        loadMessage()
        
        initVM()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                orderVM = OrderViewModel(token: token)
            }
        }
    }
    
    func loadMessage() {
        if let db = self.db {
            let count = db.unreadCount()
            if count > 0 {
                self.navigationItem.title = "\(LanguageHelper.getString(key: "MSG_LIST"))(\(count))"
            } else {
                self.navigationItem.title = "\(LanguageHelper.getString(key: "MSG_LIST"))"
            }
            messages = db.quaryData()
            tableview.reloadData()
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension MessageViewController: UITableViewDelegate, UITableViewDataSource {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "MessageTableViewCell", for: indexPath)
    }
    
    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let cell = cell as? MessageTableViewCell else {
            return
        }
        cell.initValue(message: messages[indexPath.row])
        cell.layoutSubviews()
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let textMaxSize = CGSize(width: self.view.bounds.width - 20, height: self.view.bounds.height)
        let content = messages[indexPath.row].message
        let contentSize = TextSize.textSize(text: content, font: msgContentFont, maxSize: textMaxSize)
        return contentSize.height + 100
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        //跳轉到訂單頁面
        self.readMessage(indexPath)
        self.orderDetail(indexPath)
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action1 = UITableViewRowAction(style: .destructive, title: LanguageHelper.getString(key: "DELETE")) { (action, indexPath) in
            self.deleteMessage(indexPath)
        }
        return [action1]
    }
    
    private func deleteMessage(_ indexPath: IndexPath) {
        if let db = self.db {
            db.delete(messages[indexPath.row])
            self.loadMessage()
        }
    }
    
    private func readMessage(_ indexPath: IndexPath) {
        if let db = self.db {
            db.update(messages[indexPath.row])
            self.loadMessage()
        }
    }
    
    private func orderDetail(_ indexPath: IndexPath) {
        var role: [RoleInOrder] = []
        switch messages[indexPath.row].role {
        case "RECOMMENDER":
            role.append(.recommender)
        case "MANAGER":
            role.append(.manager)
        case "CUSTOMER":
            role.append(.customer)
        default:
            break
        }
        orderVM?.getOrderDetail(id: messages[indexPath.row].orderId).subscribe(onNext: { [unowned self] orderDetail in
            if let status = orderDetail.status , status != 200 {
                self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
            } else {
                let orderStep = orderSteps[orderDetail.orderStatus!]!
                if orderStep < 6 && (role.contains(.customer) || role.contains(.manager)) {
                    let detailPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "OrderDetailViewController") as! OrderDetailViewController
                    detailPage.order = orderDetail
                    detailPage.role = role
                    self.navigationController?.pushViewController(detailPage, animated: true)
                } else if orderStep == 6 {
                    if role.contains(.customer) {
                        let detailPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "HistoryOrderDetailViewController") as! HistoryOrderDetailViewController
                        detailPage.order = orderDetail
                        detailPage.role = role
                        self.navigationController?.pushViewController(detailPage, animated: true)
                    } else if role.contains(.recommender) || role.contains(.manager) {
                        let detailPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "HistoryOrderRecommenderViewController") as! HistoryOrderRecommenderViewController
                        detailPage.order = orderDetail
                        detailPage.role = role
                        self.navigationController?.pushViewController(detailPage, animated: true)
                    }
                }
            }
        })
        .addDisposableTo(disposeBag)
    }
    
}

